package com.whmskj.xjlhsc.gongweiji.produce.service.imp;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.whmskj.xjlhbc.core.AjaxResult;
import com.whmskj.xjlhsc.gongweiji.produce.mapper.GWJProductionMapper;
import com.whmskj.xjlhsc.gongweiji.produce.pojo.dto.*;
import com.whmskj.xjlhsc.gongweiji.produce.pojo.entity.ListOfVarietiesAndYields;
import com.whmskj.xjlhsc.gongweiji.produce.pojo.entity.VarietiesAndYields;
import com.whmskj.xjlhsc.gongweiji.produce.pojo.entity.Varieyies;
import com.whmskj.xjlhsc.gongweiji.produce.pojo.vo.*;
import com.whmskj.xjlhsc.gongweiji.produce.service.IGWJProductionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author jiaruchun
 * @date 2025-09-24 21:34
 */
@Slf4j
@Service
public class GWJProductionServiceImpl implements IGWJProductionService {
    @Autowired
    private GWJProductionMapper gwjProductionMapper;

    @Override
    public PageResult<DailyVO> daily(DailyDTO dto) {
        //默认分页参数
        Integer pageNum = dto.getPageNum() != null ? dto.getPageNum() : 1;
        Integer pageSize = dto.getPageSize() != null ? dto.getPageSize() : 10;
        PageHelper.startPage(pageNum, pageSize);
        com.github.pagehelper.Page<DailyVO> daily = (com.github.pagehelper.Page) gwjProductionMapper.daily(dto);
        log.info("GWJProductionServiceImpl daily dto:{}", dto);
        return new PageResult<>(daily.getTotal(), daily.getResult());
    }

    @Override
    public List<WorkshopVO> getWorkshopList() {
        return gwjProductionMapper.getWorkshopList();
    }

    @Override
    public MonthVO month(MonthDTO dto) {
        String month = dto.getMonth(); // yyyy-MM
        String start;
        String end;

        LocalDateTime now = LocalDateTime.now();
        YearMonth yearMonth;
        if (month == null || month.isEmpty()) {
            yearMonth = YearMonth.from(now);
        } else {
            yearMonth = YearMonth.parse(month); // 解析 yyyy-MM
        }

// 当前月的20号 21:30
        LocalDateTime curMonth20_2130 = yearMonth.atDay(20).atTime(21, 30);

// 上个月的20号
        LocalDate prevMonth20 = yearMonth.minusMonths(1).atDay(20);

        if (yearMonth.equals(YearMonth.from(now))) {
            // 如果传入的month是当前月
            if (now.isAfter(curMonth20_2130)) {
                // 已经过了本月20号21:30
                end = now.toLocalDate().toString();
                start = yearMonth.atDay(20).toString();
            } else {
                // 还没到本月20号21:30
                end = yearMonth.atDay(20).toString();
                start = prevMonth20.toString();
            }
        } else {
            // 非当前月
            start = prevMonth20.toString();
            end = yearMonth.atDay(20).toString();
        }
        Float production = 0f;
        Float plan = 0f;
        Float efficiency = 0f;
        List<MonthDetailVOList> monthList = gwjProductionMapper.getMonthList(start,end, dto.getProcess());
        if (!CollectionUtils.isEmpty(monthList)) {
            for (MonthDetailVOList monthDetailVOList : monthList) {
                Float lateShiftProduction = monthDetailVOList.getLateShiftProductionKg() != null ? monthDetailVOList.getLateShiftProductionKg() : 0f;
                Float earlyShiftProduction = monthDetailVOList.getEarlyShiftProductionKg() != null ? monthDetailVOList.getEarlyShiftProductionKg() : 0f;
                Float lateShiftEfficiency = monthDetailVOList.getLateShiftEfficiency() != null ? monthDetailVOList.getLateShiftEfficiency() : 0f;
                Float earlyShiftEfficiency = monthDetailVOList.getEarlyShiftEfficiency() != null ? monthDetailVOList.getEarlyShiftEfficiency() : 0f;

                production += lateShiftProduction + earlyShiftProduction;

                // 避免除以零
                if (lateShiftEfficiency != 0 && earlyShiftEfficiency != 0) {
                    plan += (lateShiftProduction / (lateShiftEfficiency / 100)) +
                            (earlyShiftProduction / (earlyShiftEfficiency / 100));
                }
            }
            if (plan > 0) {
                efficiency = production / plan;
            } else {
                efficiency = 0f;
            }
        }
        //efficiency乘以100保留两位
        efficiency = (float) (Math.round(efficiency * 10000.0) / 100.0);
        //plan保留两位
        plan = (float) (Math.round(plan * 100.0) / 100.0);
        //production保留两位
        production = (float) (Math.round(production * 100.0) / 100.0);
        HashMap<String, List<MonthDetailVOLists>> stringListHashMap = new HashMap<>();
        //key为不同机台,
        for (MonthDetailVOList monthDetailVOList : monthList) {
            String machineNumber = monthDetailVOList.getMachineNumber();
            MonthDetailVOLists monthDetailVOLists = new MonthDetailVOLists();
            monthDetailVOLists.setDate(monthDetailVOList.getDate());
            monthDetailVOLists.setShiftLate(monthDetailVOList.getShiftLate());
            monthDetailVOLists.setLateShiftProductionKm(monthDetailVOList.getLateShiftProductionKm());
            monthDetailVOLists.setLateShiftProductionKg(monthDetailVOList.getLateShiftProductionKg());
            monthDetailVOLists.setLateShiftEfficiency(monthDetailVOList.getLateShiftEfficiency());
            monthDetailVOLists.setShiftEarly(monthDetailVOList.getShiftEarly());
            monthDetailVOLists.setEarlyShiftProductionKm(monthDetailVOList.getEarlyShiftProductionKm());
            monthDetailVOLists.setEarlyShiftProductionKg(monthDetailVOList.getEarlyShiftProductionKg());
            monthDetailVOLists.setEarlyShiftEfficiency(monthDetailVOList.getEarlyShiftEfficiency());
            if (stringListHashMap.containsKey(machineNumber)) {
                stringListHashMap.get(machineNumber).add(monthDetailVOLists);
            } else {
                List<MonthDetailVOLists> monthDetailVOLists1 = new ArrayList<>();
                monthDetailVOLists1.add(monthDetailVOLists);
                stringListHashMap.put(machineNumber, monthDetailVOLists1);
            }
        }
        return new MonthVO(production, plan, efficiency, stringListHashMap);
    }
    @Override
    public List<Varieyies> processVariety(String process) {
        return gwjProductionMapper.processVariety(process);
    }

    @Override
    public CompletionRateVOO completionRate(CompletionRateDTO dto) {
        //表格
        PageHelper.startPage(dto.getPageNum()!= null ? dto.getPageNum() : 1, dto.getPageSize()!= null ? dto.getPageSize() : 10);
        List<CompletionRateVO> completionRate = gwjProductionMapper.getCompletionRate(dto);
        com.github.pagehelper.Page<CompletionRateVO> completionRate1 = (com.github.pagehelper.Page<CompletionRateVO>) completionRate;
        log.info("GWJProductionServiceImpl completionRate dto:{}", dto);
        //统计图
        List<ListOfVarietiesAndYields> listOfVarietiesAndYields = new ArrayList<>();
        if(!completionRate.isEmpty()){
            listOfVarietiesAndYields = completionRate.stream()
                    .collect(Collectors.groupingBy(CompletionRateVO::getDate))
                    .entrySet().stream()
                    .map(dateEntry -> {
                        String date = dateEntry.getKey();
                        List<CompletionRateVO> dailyData = dateEntry.getValue();

                        List<VarietiesAndYields> varietiesAndYieldsList = dailyData.stream()
                                .collect(Collectors.groupingBy(
                                        CompletionRateVO::getVariety,
                                        Collectors.summingDouble(item -> item.getTotalActualProductionKg() != null ? item.getTotalActualProductionKg() : 0.0)
                                ))
                                .entrySet().stream()
                                .map(varietyEntry -> {
                                    VarietiesAndYields varietiesAndYields = new VarietiesAndYields();
                                    varietiesAndYields.setVarieties(varietyEntry.getKey());
                                    varietiesAndYields.setYield(varietyEntry.getValue().floatValue());
                                    return varietiesAndYields;
                                })
                                .collect(Collectors.toList());

                        ListOfVarietiesAndYields listItem = new ListOfVarietiesAndYields();
                        listItem.setDate(date);
                        listItem.setVarietiesAndYieldsList(varietiesAndYieldsList);
                        return listItem;
                    })
                    .sorted(Comparator.comparing(ListOfVarietiesAndYields::getDate))
                    .collect(Collectors.toList());
        }
        Map<String,List<ListOfVarietiesAndYield>> completionRateMap = new HashMap<>();
        if (!listOfVarietiesAndYields.isEmpty()) {
            for (ListOfVarietiesAndYields ofVarietiesAndYield : listOfVarietiesAndYields) {
                completionRateMap.put(ofVarietiesAndYield.getDate(), ofVarietiesAndYield.getVarietiesAndYieldsList().stream()
                        .map(varietiesAndYields -> new ListOfVarietiesAndYield(varietiesAndYields.getVarieties(), varietiesAndYields.getYield()))
                        .collect(Collectors.toList()));
            }
        }
        return new CompletionRateVOO(completionRateMap, new PageResult<>(completionRate1.getTotal(),completionRate1.getResult()));
    }

    @Override
    public List<ConversionRateVO> conversionRate(ConversionRateDTO dto) {
        return gwjProductionMapper.getConversionRate(dto.getVariety(), dto.getProcess(), dto.getMonth());
    }

    @Override
    public DetailDailyVOs detailDaily(DetailDailyDTO dto) {
        PageHelper.startPage(dto.getPageNum()!= null ? dto.getPageNum() : 1, dto.getPageSize()!= null ? dto.getPageSize() : 10);
        List<DetailDailyVo> detailDaily = gwjProductionMapper.getDetailDaily(dto);
        com.github.pagehelper.Page<DetailDailyVo> detailDaily1 = (com.github.pagehelper.Page<DetailDailyVo>) detailDaily;
        log.info("GWJProductionServiceImpl detailDaily dto:{}", dto);
        //开台数
        Integer openTableCount = detailDaily.stream().map(DetailDailyVo::getOpenNum).reduce(Integer::sum).orElse(0);
        //本日计划，吨,除以1000
        Float planYield = detailDaily.stream().map(DetailDailyVo::getPlanYield).reduce(Float::sum).orElse(0f) / 1000;
        //本日实际，吨,除以1000
        Float actualYield = detailDaily.stream().map(DetailDailyVo::getActualYield).reduce(Float::sum).orElse(0f) / 1000;
        //本日增减，吨,除以1000
        Float yieldChange = detailDaily.stream().map(DetailDailyVo::getYieldChange).reduce(Float::sum).orElse(0f) / 1000;
        //本日止计划，吨,除以1000
        Float stopPlanYield = detailDaily.stream().map(DetailDailyVo::getPlanStop).reduce(Float::sum).orElse(0f) / 1000;
        //本日止实际，吨,除以1000
        Float stopActualYield = detailDaily.stream().map(DetailDailyVo::getActualStop).reduce(Float::sum).orElse(0f) / 1000;
        //本日止增减，吨,除以1000
        Float stopYieldChange = detailDaily.stream().map(DetailDailyVo::getStopChange).reduce(Float::sum).orElse(0f) / 1000;
        return new DetailDailyVOs(openTableCount, planYield, actualYield, yieldChange, stopPlanYield, stopActualYield, stopYieldChange, new PageResult<>(detailDaily1.getTotal(),detailDaily1.getResult()));
    }
}
